<template>
	<div class="padding-across-10" v-loading="loading" element-loading-text="拼命加载中">
		<div style="width:100%;">
			<el-row>
				<el-col :span="8">
					<headerOpreate :opreate-datas="opreateDatas" v-on:executeAction="executeAction"></headerOpreate>
				</el-col>
				<el-col :span="16">
					<div style="text-align: right">
						<span style="font-size: 13px;font-weight: bold">检索字段</span>
						<el-select style="margin-top: 2px;width: 90px" size="small" v-model="findType" placeholder="检索字段">
							<el-option label="名称" :value="0"></el-option>
							<el-option label="设备码" :value="1"></el-option>
						</el-select>
						<span style="font-size: 13px;font-weight: bold">关键字</span>
						<el-input style="width: 160px" v-model="keyWord" size="small" placeholder="查询关键字">
							<el-button id="searchDeviceData" slot="append" icon="search" @click="findDevices"></el-button>
						</el-input>
						<span style="font-size: 13px;font-weight: bold">设备种类</span>
						<el-select style="width: 140px" size="small" v-model="deviceType" placeholder="请选择设备类型" @change="selectDeviceType">
							<el-option v-for="item in deviceTypeDatas" :key="item.name" :label="item.value" :value="item.name">
							</el-option>
						</el-select>
						<span style="font-size: 13px;font-weight: bold">状态</span>
						<el-select style="width: 80px" size="small" v-model="deviceStatus" placeholder="请选择设备状态" @change="selectDeviceStatus">
							<el-option label="全部" :value="0"></el-option>
							<el-option label="在线" :value="1"></el-option>
							<el-option label="离线" :value="2"></el-option>
						</el-select>
					</div>
				</el-col>
			</el-row>
			<div>
				<div style="width: 250px;float: left;">
					<div style="padding-top: 9px;">
						<i class="fa fa-circle" style="color:#13ce66"></i>
						<span style="font-size: 15px">{{'在线('+onlineTotal+')'}}</span>
						<i class="fa fa-circle" style="color: #48576a"></i>
						<span style="font-size: 15px">{{'离线('+offlineTotal+')'}}</span>
					</div>
				</div>
				<div class="block" style="text-align:right;float: right;padding: 1px 0">
					<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[10, 20, 30, 40, 50]" :page-size="pageSize" layout="total, sizes,prev, pager, next, jumper" :total="totalSize">
					</el-pagination>
				</div>
			</div>
			<el-table border style="width: 100%" :data="tableData" @selection-change="handleSelectionChange">
				<el-table-column :show-overflow-tooltip="true" type="selection"></el-table-column>
				<el-table-column :show-overflow-tooltip="true" label="名称" align="center" prop="name"></el-table-column>
				<el-table-column :show-overflow-tooltip="true" label="设备码" align="center" prop="sn"></el-table-column>
				<el-table-column :show-overflow-tooltip="true" label="型号" align="center" prop="model"></el-table-column>
				<el-table-column :show-overflow-tooltip="true" label="状态" align="center">
					<template slot-scope="scope">
						<el-tag v-if="scope.row.online" type="success">
							<li class="el-icon-circle-check el-icon--left"></li>在线
						</el-tag>
						<el-tag v-else type="gray">
							<li class="el-icon-circle-close el-icon--left"></li>离线
						</el-tag>
					</template>
				</el-table-column>
			</el-table>
			<div class="block" style="text-align:right;margin-bottom:60px;">
				<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[10, 20, 30, 40, 50]" :page-size="pageSize" layout="total, sizes,prev, pager, next, jumper" :total="totalSize">
				</el-pagination>
			</div>
			<el-dialog title="区域列表" v-model="districtDialog" :show-close="false" :class="[dialog-tiny-width]">
				<el-tree :show-overflow-tooltip="true" style="height: 300px;overflow: auto;border: 0" ref="tree" :data="districtsDatas" :props="defaultProps" node-key="DistrictKeyId" :highlight-current="true" :current-node-key="currentNodeKey" :default-expanded-keys="defaultExpandedKeys" :expand-on-click-node="false" @node-click="handleNodeClick">
				</el-tree>
				<div slot="footer" class="dialog-footer">
					<el-button @click="districtDialog = false">取 消</el-button>
					<el-button type="primary" @click="confirmAddDevices">确 定</el-button>
				</div>
			</el-dialog>
		</div>
	</div>
</template>
<script>
	import $ from 'jquery'
	import { GloabFun, HttpServer } from '../../../../assets/js/common.js'
	import headerOpreate from '../../../../components/headerOpreate'
	let id = 1000;
	export default {
		components: {
			headerOpreate
		},
		data() {
			//回车触发查询按钮
			document.onkeydown = function(event) {
				var e = event || window.event;
				if(e && e.keyCode == 13) { //回车键的键值为13
					$("#searchDeviceData").click(); //调用登录按钮的登录事件
				}
			};
			return {
				isReload: false,
				loading: false,
				keyWord: '',
				findType: 0,
				deviceTypeDatas: [],
				deviceType: '',
				deviceStatus: 0,
				currentNodeKey: null,
				districtDialog: false,
				districtsDatas: [],
				defaultExpandedKeys: [],
				hasBindDistricts: [],
				offlineTotal: '0',
				onlineTotal: '0',
				tableData: [],
				multipleSelection: [],
				currentPage: 1,
				pageSize: 10,
				totalSize: 0,
				defaultProps: {
					children: 'Children',
					label: 'Name',
					id: 'Id'
				},
				opreateDatas: [{
						show: true,
						size: "small",
						type: 'primary',
						icon: 'el-icon-eleg-icon_refresh el-icon--left',
						name: this.$t("message.refresh"),
						action: 'reloadDatas'
					},
					{
						show: GloabFun.getUid() == 'admin' ? true : false,
						size: "small",
						type: "primary",
						icon: "el-icon-plus el-icon--left",
						name: "添加",
						action: "addMultiple"
					},
					{
						show: GloabFun.getUid() == 'admin' ? true : false,
						type: "primary",
						size: "small",
						icon: "el-icon-upload2 el-icon--left",
						name: "注册智能空开",
						action: "registerAirSwitch"
					},
					{
						show: GloabFun.getUid() == 'admin' ? true : false,
						type: "danger",
						size: "small",
						icon: "el-icon-delete2 el-icon--left",
						name: "删除",
						action: "deleteMultiple"
					}
				],
				bindDeviceForm: {
					districtId: '',
					name: ''
				}
			}
		},
		props: {
			subArgs: {
				type: Object,
				default: function() {
					return {};
				}
			}
		},
		methods: {
			executeAction(action) {
				if(action) {
					this[action]();
				}
			},
			handleCurrentChange(val) {
				this.currentPage = val;
				this.getAllDeviceDatas();
			},
			handleSizeChange(val) {
				this.pageSize = val;
				this.getAllDeviceDatas();
			},
			//批量进行托管
			handleSelectionChange(val) {
				this.multipleSelection = val;
			},
			//用于添加设备
			formateSelection() {
				var result = [],
					array = this.multipleSelection;
				for(var i = 0; i < array.length; i++) {
					result.push(array[i].sn)
				}
				return result;
			},
			//用于删除未托管设备
			formateSelection1() {
				var result = [],
					array = this.multipleSelection;
				for(var i = 0; i < array.length; i++) {
					result.push(array[i].keyid)
				}
				return result;
			},
			//批量删除未托管设备
			deleteMultiple() {
				if(this.formateSelection1().length > 0) {
					this.$confirm('此操作将删除此设备，是否继续?', '提示', {
						confirmButtonText: this.$t('message.yes'),
						cancelButtonText: this.$t('message.no'),
						type: 'warning'
					}).then(() => {
						//批量进行托管
						HttpServer.httpPost.call(this, '/Api/Device/Delete/UnmanagedDevice', {
							id: this.formateSelection1()
						}, function(response) {}, function(response) {
							if(response.data.code === 0) {
								this.getAllDeviceDatas();
								this.$notify({
									title: '成功',
									message: '操作成功',
									type: 'success',
									duration: 2500
								});
							} else {
								this.$notify.error({
									title: '错误',
									message: response.data.msg,
									duration: 2500
								});
							}
						});

					}).catch(() => {
						this.$notify.info({
							title: '消息',
							message: this.$t('message.cancleOperation'),
							duration: 2500
						})
					});
				} else {
					this.$notify({
						title: this.$t('message.warning'),
						message: this.$t('message.selectBulkAddWarning'),
						type: 'warning',
						duration: 2500
					});
				}
			},
			//选择区域
			handleNodeClick(data) {
				// console.log('data',data);
				this.bindDeviceForm.districtId = data.DistrictKeyId;
				this.bindDeviceForm.name = data.Name;
			},
			//选择设备状态
			selectDeviceStatus() {
				this.getAllDeviceDatas();
			},
			array_contain(array, obj) {
				for(var i = 0; i < array.length; i++) {
					if(array[i] === obj) //如果要求数据类型也一致，这里可使用恒等号===
						return true;
				}
				return false;
			},
			sortDatas(arr) {
				for(var i = 0; i < arr.length; i++) {
					for(var j = i + 1; j < arr.length; j++) {
						if(arr[i].DistrictKeyId > arr[j].DistrictKeyId) {
							var tmp = arr[i];
							arr[i] = arr[j];
							arr[j] = tmp;
						}
					}
				}
				return arr;
			},
			getUserDistrictsDatas() {
				//查询用户绑定区域
				HttpServer.httpGet.call(this, '/Api/District/districtTree?uid=' + parseInt(GloabFun.getKeyId()), function(response) {}, function(response) {
					// console.log('获取当前用户的所有绑定区域信息',response)
					if(response.data.code === 0) {
						if(response.data.info.length > 0) {
							this.districtsDatas = this.sortDatas(response.data.info);
							this.hasBindDistricts = response.data.childids;
							this.bindDeviceForm.districtId = this.districtsDatas[0].DistrictKeyId;;
							this.currentNodeKey = this.districtsDatas[0].DistrictKeyId;
							this.bindDeviceForm.name = this.districtsDatas[0].Name;
							this.defaultExpandedKeys.push(this.districtsDatas[0].DistrictKeyId);
						}
					}
				});
			},
			//批量添加设备
			addMultiple() {
				if(this.formateSelection1().length > 0) {
					this.districtDialog = true;
					this.getUserDistrictsDatas();
				} else {
					this.$notify({
						title: this.$t('message.warning'),
						message: '请选择要添加的设备',
						type: 'warning',
						duration: 2500
					});
				}
			},
			registerAirSwitch() {
				HttpServer.httpGet.call(this, '/Api/AirSwitch/RegisterEBox', res => {}, res => {
					if(res.data.code === 0) {
						this.$notify({
							title: this.$t('message.success'),
							message: '注册成功',
							type: 'success',
							duration: 2000
						});
					} else {
						this.$notify({
							title: this.$t('message.warning'),
							message: res.data.message,
							type: 'warning',
							duration: 2000
						});
					}
				});
			},
			//添加设备
			confirmAddDevices() {
				if(this.array_contain(this.hasBindDistricts, this.bindDeviceForm.districtId)) {
					this.$confirm('此操作将在' + this.bindDeviceForm.name + '下添加此设备，是否继续？', '提示', {
						confirmButtonText: this.$t('message.yes'),
						cancelButtonText: this.$t('message.no'),
						type: 'warning'
					}).then(() => {
						//批量添加
						this.loading = true;
						var bindInfo = [];
						for(var i = 0; i < this.formateSelection1().length; i++) {
							bindInfo[i] = {};
							bindInfo[i].districtId = this.bindDeviceForm.districtId;
							bindInfo[i].deviceId = this.formateSelection1()[i];
						}
						HttpServer.httpPost.call(this, '/Api/District/DeviceBind', {
							info: bindInfo
						}, function(response) {}, function(response) {
							this.loading = false;
							if(response.data.code === 0) {
								this.getAllDeviceDatas();
								this.$notify({
									title: '成功',
									message: this.$t('message.addSuccess'),
									type: 'success',
									duration: 2500
								});
								this.districtDialog = false;
							} else {
								this.$notify.error({
									title: '错误',
									message: response.data.msg,
									duration: 2500
								});
							}
						});
					}).catch(() => {
						this.$notify.info({
							title: '消息',
							message: this.$t('message.cancleOperation'),
							duration: 2500
						})
					});
				} else {
					this.$notify({
						title: this.$t('message.warning'),
						message: '无对' + this.bindDeviceForm.name + '的操作权限',
						type: 'warning',
						duration: 2500
					});
				}
			},
			selectDeviceType() {
				this.getAllDeviceDatas();
			},
			//查找设备
			findDevices() {
				this.getAllDeviceDatas();
			},
			//刷新
			reloadDatas() {
				this.isReload = true;
				this.getAllDeviceDatas();
			},
			//查询设备
			getAllDeviceDatas() {
				//获取所有未托管设备
				this.loading = true;
				HttpServer.httpPost.call(this, '/api/device/info/unManaged', {
					pagesize: this.pageSize,
					index: this.currentPage,
					category: this.deviceType !== '' ? [this.deviceType] : [],
					name: this.findType === 0 ? this.keyWord : '',
					sn: this.findType === 1 ? this.keyWord : '',
					isonline: this.deviceStatus
				}, function(response) {}, function(response) {
					this.loading = false;
					// console.log('未添加设备',response)
					if(response.data.code === 0) {
						this.totalSize = response.data.totalcount;
						this.tableData = response.data.deviceinfo;
						this.offlineTotal = response.data.offlinecount;
						this.onlineTotal = response.data.onlinecount;
						if(this.isReload) {
							this.$notify({
								title: '成功',
								message: this.$t('message.refreshSuccess'),
								type: 'success',
								duration: 2500
							});
						}
					} else {
						this.$notify.error({
							title: '错误',
							message: response.data.msg,
							duration: 2500
						});
					}
					this.isReload = false;
				});
			},
			//获取设备种类并查询设备
			getDatas() {
				HttpServer.httpGet.call(this, '/Api/Device/GetAllDeviceCategory?fromwhat=0', function(resp) {}, function(resp) {
					resp.data.unshift({
						name: '',
						value: '全部'
					});
					this.deviceTypeDatas = resp.data;
					this.deviceType = this.deviceTypeDatas[0].name;
					this.getAllDeviceDatas();
				})
			}
		},
		created() {
			this.getDatas();
		}
	}
</script>
<style scoped lang="less">
	.name {
		color: #20a0ff;
	}
	
	.list {
		height: 500px;
		// max-height:480px;
		width: 16%;
		float: left;
		overflow: auto;
		overflow-x: auto;
		// background-color: #324157;
		margin-bottom: 10px;
		.panel_title {
			height: 28px;
			line-height: 28px;
			font-size: 10px;
			text-align: center;
			border: 1px solid #E0E0E0;
			border-radius: 5px;
			color: #fff;
			background-color: #324157;
		}
		// color:#fff
	}
</style>